'use client'

import React from 'react'
import { Button } from '@/components/ui/button'
import { Download } from 'lucide-react'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js'
import { Bar } from 'react-chartjs-2'

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
)

interface FunnelData {
  [key: string]: {
    pv: number[]
    uv: number[]
  }
}

interface FunnelChartProps {
  data: FunnelData
  steps: string[]
}

const colors = {
  total: {
    primary: 'rgba(156, 163, 175, 0.8)',
    secondary: 'rgba(156, 163, 175, 0.4)',
  },
  tangzhuang: {
    primary: 'rgba(59, 130, 246, 0.8)',
    secondary: 'rgba(59, 130, 246, 0.4)',
  },
  movie: {
    primary: 'rgba(16, 185, 129, 0.8)',
    secondary: 'rgba(16, 185, 129, 0.4)',
  },
  hanfu: {
    primary: 'rgba(249, 115, 22, 0.8)',
    secondary: 'rgba(249, 115, 22, 0.4)',
  },
  aivideo: {
    primary: 'rgba(139, 92, 246, 0.8)',
    secondary: 'rgba(139, 92, 246, 0.4)',
  }
}

const metricLabels = {
  total: '总计',
  tangzhuang: '唐装写真',
  movie: '热门影视剧妆造',
  hanfu: '制式汉服',
  aivideo: 'AI唐风视频'
}

export function FunnelChart({ data, steps }: FunnelChartProps) {
  const [dataType, setDataType] = React.useState<'pv' | 'uv'>('pv')

  // 计算总量数据
  const totalData = {
    pv: steps.map((_, index) => 
      Object.values(data).reduce((sum, curr) => sum + curr.pv[index], 0)
    ),
    uv: steps.map((_, index) => 
      Object.values(data).reduce((sum, curr) => sum + curr.uv[index], 0)
    )
  }

  const chartData = {
    labels: steps,
    datasets: [
      // 总量数据
      {
        label: '总计',
        data: totalData[dataType],
        backgroundColor: colors.total.primary,
        borderColor: colors.total.primary,
        borderWidth: 1,
        barPercentage: 0.9,
        categoryPercentage: 0.8,
        order: 1, // 确保总量在最底层
      },
      // 各模块数据
      ...Object.entries(data).map(([metric, values], index) => ({
        label: metricLabels[metric as keyof typeof metricLabels],
        data: values[dataType],
        backgroundColor: colors[metric as keyof typeof colors].primary,
        borderColor: colors[metric as keyof typeof colors].primary,
        borderWidth: 1,
        barPercentage: 0.9,
        categoryPercentage: 0.8 / Object.keys(data).length,
        order: 0, // 确保模块数据在上层
      })),
    ],
  }

  const options = {
    responsive: true,
    maintainAspectRatio: false,
    indexAxis: 'y' as const,
    plugins: {
      legend: {
        position: 'top' as const,
      },
      tooltip: {
        callbacks: {
          label: (context: any) => {
            const label = context.dataset.label || ''
            const value = context.raw || 0
            const total = totalData[dataType][0]
            const percentage = ((value / total) * 100).toFixed(1)
            let tooltipText = `${label}: ${value}`
            
            // 添加占总量的百分比
            if (label !== '总计') {
              tooltipText += ` (总量占比: ${percentage}%)`
            }
            
            // 添加转化率
            if (context.dataIndex > 0) {
              const prevValue = context.dataset.data[context.dataIndex - 1]
              const conversionRate = ((value / prevValue) * 100).toFixed(1)
              tooltipText += ` [转化率: ${conversionRate}%]`
            }
            
            return tooltipText
          },
        },
      },
    },
    scales: {
      x: {
        stacked: false,
        grid: {
          display: false,
        },
        title: {
          display: true,
          text: dataType.toUpperCase(),
        }
      },
      y: {
        stacked: false,
        grid: {
          display: false,
        },
      },
    },
  }

  const handleDownloadCSV = () => {
    const headers = [
      '步骤',
      '总计',
      ...Object.keys(data).map(metric => 
        `${metricLabels[metric as keyof typeof metricLabels]}`
      )
    ]
    const rows = steps.map((step, i) => [
      step,
      totalData[dataType][i],
      ...Object.entries(data).map(([_, values]) => values[dataType][i])
    ])
    
    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.join(','))
    ].join('\n')

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `funnel_${dataType}_data.csv`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <Tabs value={dataType} onValueChange={(value) => setDataType(value as 'pv' | 'uv')}>
          <TabsList>
            <TabsTrigger value="pv">访问量 (PV)</TabsTrigger>
            <TabsTrigger value="uv">访客数 (UV)</TabsTrigger>
          </TabsList>
        </Tabs>
        <Button variant="outline" size="sm" onClick={handleDownloadCSV}>
          <Download className="mr-2 h-4 w-4" />
          下载数据
        </Button>
      </div>
      <div className="h-[400px]">
        <Bar data={chartData} options={options} />
      </div>
    </div>
  )
}